<template>
  <div class="user">
    <PageSearch :searchFormConfig="searchFormConfig" />
    <div class="content">
      <PageContent
        :contentTableConfig="contentTableConfig"
        pageName="role"
        @newBtnClick="handleNewData"
        @editClick="handleEditData"
      />
    </div>
    <PageModal
      ref="pageModalRef"
      pageName="role"
      :modalConfig="modalConfig"
      :defaultInfo="defaultInfo"
      :otheerInfo="otheerInfo"
    >
      <div class="menu-tree">
        <el-tree
          ref="elTreeRef"
          :data="menus"
          show-checkbox
          node-key="id"
          :props="{
            children: 'children',
            label: 'name'
          }"
          @check="handleCheckChange"
        />
      </div>
    </PageModal>
  </div>
</template>

<script lang="ts">
import PageContent from '@/components/page-content'
import PageSearch from '@/components/page-search'

import { computed, defineComponent, nextTick, ref } from 'vue'
import { ElTree } from 'element-plus'
import { searchFormConfig } from './search.config'
import { contentTableConfig } from './content.config'
import { modalConfig } from './configs/modal.config'
import PageModal from '@/components/page-modal/src/page-modal.vue'
import { usePageModal } from '@/hooks/use-page-modal'
import { useStore } from '@/store'
import { menuMapLeafKeys } from '@/utils/map-menus'

export default defineComponent({
  name: 'role',
  components: { PageContent, PageSearch, PageModal },
  setup() {
    const elTreeRef = ref<InstanceType<typeof ElTree>>()
    //处理pageModal的hook
    const editCallback = (item: any) => {
      console.log(item, '回调')
      const leafKeys = menuMapLeafKeys(item.menuList)
      console.log(leafKeys)
      nextTick(() => {
        elTreeRef.value?.setCheckedKeys(leafKeys, false)
      })
    }
    //引入hooks
    const [pageModalRef, defaultInfo, handleEditData, handleNewData] =
      usePageModal(undefined, editCallback)

    const store = useStore()
    const otheerInfo = ref({})
    const menus = computed(() => store.state.entireMenu)
    const handleCheckChange = (data1: any, data2: any) => {
      const checkedKeys = data2.checkedKeys
      const checkedKhalfCheckedKeys = data2.halfCheckedKeys
      const menuList = [...checkedKeys, ...checkedKhalfCheckedKeys]
      otheerInfo.value = { menuList }
    }
    return {
      contentTableConfig,
      searchFormConfig,
      modalConfig,
      pageModalRef,
      defaultInfo,
      handleEditData,
      handleNewData,
      menus,
      otheerInfo,
      handleCheckChange,
      elTreeRef
    }
  }
})
</script>

<style scoped>
.user {
  background: white;
}
.menu-tree {
  margin-left: 25px;
}
</style>
